package xyz.zchao.blog.controller;

import org.apache.commons.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.zchao.blog.annotation.IgnoreToken;
import xyz.zchao.blog.pojo.Comment;
import xyz.zchao.blog.pojo.User;
import xyz.zchao.blog.service.CommentService;
import xyz.zchao.blog.service.UserService;
import xyz.zchao.blog.util.ResultCode;
import xyz.zchao.blog.util.ResultVO;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @Description: 评论留言处理
 * @Author: guozongchao
 * @Date: 2020/5/10 11:43
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    private static final Logger log = LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;

    /**
     * 获取评论列表
     * 参数articleId为可选参数,如果带有该参数，则请求查询该参数对应的文章的评论
     * @param articleId
     * @return
     */
    @IgnoreToken
    @GetMapping("/list")
    public ResultVO getComments(@RequestParam(required = false) Integer articleId) {
        List<Comment> parentComments=commentService.getParentComments(articleId);
        return new ResultVO(ResultCode.SUCCESS,parentComments);
    }

    /**
     * 添加评论
     * @param record
     * @return
     */
    @PostMapping("/add")
    public ResultVO addComment(@RequestBody @Valid Comment record, HttpServletRequest request){
        //从session中获取登录的发表评论用户
        Integer userId = (Integer) request.getAttribute("userId");
        record.setUserId(userId);
        if(commentService.create(record)>0){
            //添加成功后返回相应的记录
            Comment comment =commentService.retrieveById(record.getCommentId());
            return new ResultVO<Comment>(ResultCode.SUCCESS,comment);
        }
        return new ResultVO(ResultCode.FAILED, null);
    }

}
